<template>
  <!-- 收益看板 -->
  <a-tabs v-model:activeKey="activeKey" @change="changeTab">
    <a-tab-pane :key="1" tab="时间维度统计" />
    <a-tab-pane :key="2" tab="企业维度统计" />
  </a-tabs>
  <div class="filterContainer">
    <div class="filterItem">
      <div>
        <div class="filterLabel">时间类型：</div>
        <a-select
          v-model:value="filterForm.timeType"
          class="filterSelect"
          placeholder="按年"
          @change="handleChangeTimeType"
        >
          <a-select-option :value="2">按年</a-select-option>
          <a-select-option :value="1">按月</a-select-option>
        </a-select>
      </div>
      <div>
        <div class="filterLabel" style="margin-top: 15px">时间选择：</div>
        <a-date-picker
          v-model:value="filterForm.year"
          picker="year"
          class="filterSelect"
          format="YYYY"
          valueFormat="YYYY"
          v-if="filterForm.timeType === 2"
          @change="changeOption"
          :allowClear="false"
        />
        <a-date-picker
          v-model:value="filterForm.month"
          picker="month"
          class="filterSelect"
          format="YYYY-MM"
          valueFormat="YYYY-MM"
          v-else
          @change="changeOption"
          :allowClear="false"
        />
      </div>

      <!-- <a-select
        v-model:value="filterForm.year"
        class="filterSelect"
        placeholder="按年"
        style="margin-top: 15px"
        :allow-clear="true"
      >
        <a-select-option value="2025">2025</a-select-option>
      </a-select> -->
    </div>
    <div class="filterItem">
      <div class="filterLabel">选择企业：</div>
      <a-select
        v-model:value="filterForm.stationId"
        class="filterSelect"
        placeholder="请选择"
        show-search
        optionFilterProp="label"
        :allow-clear="true"
        :disabled="activeKey === 2"
        @change="getIncomePlate"
      >
        <a-select-option
          v-for="item in companyList"
          :key="item.id"
          :value="item.id"
          :label="item.name"
          :disabled="!item.haveIncomeResult"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
    </div>
    <div class="filterItem">
      <div class="filterLabel">导出年份：</div>
      <div class="exportGroup">
        <a-date-picker
          v-model:value="filterForm.exportYear"
          picker="year"
          class="filterSelect yearSelect"
          format="YYYY"
          valueFormat="YYYY"
        />
        <!-- <a-select
          v-model:value="filterForm.exportYear"
          class="filterSelect yearSelect"
          placeholder="请选择"
          :allow-clear="true"
        >
          <a-select-option value="2024">2024年</a-select-option>
        </a-select> -->
        <a-button type="link" class="exportBtn" @click="exportIncomePlate"
          >导出</a-button
        >
        <!-- :disabled="!filterForm.exportYear" -->
      </div>
    </div>
  </div>
  <div class="nav">
    <div class="navContent">
      <div
        v-for="(item, index) in cardList"
        :key="index"
        class="card"
        :class="item.colorClass"
      >
        <div class="cardIcon">
          <component :is="item.icon" />
        </div>
        <div class="cardContent">
          <div class="cardValue">{{ item.value }}元</div>
          <div class="cardLabel">
            {{ item.label }}
            <a-tooltip v-if="item.tips" :title="item.tips">
              <InfoCircleOutlined />
            </a-tooltip>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!--  <div class="revenueChart">
    <h2 class="chartTitle">收益构成</h2>
    <div ref="chartRef" class="pieChart"></div>
    <div class="legendList">
      <div class="legendItem">
        <span class="legendDot electricity"></span>
        <span class="legendLabel">售电收益</span>

        <span class="legendValue"
          >{{
            isNaN(revenueProportion.saleIncomeRate)
              ? "--"
              : revenueProportion.saleIncomeRate
          }}%</span
        >
      </div>
      <div class="legendItem">
        <span class="legendDot storage"></span>
        <span class="legendLabel">储能收益</span>
        <span class="legendValue"
          >{{
            isNaN(revenueProportion.storageIncomeRate)
              ? "--"
              : revenueProportion.storageIncomeRate
          }}%</span
        >
      </div>
    </div>
  </div> -->
  <div class="barChartContainer">
    <div ref="barChartRef" class="barChart"></div>
  </div>
</template>
<script setup>

import * as echarts from "echarts"
import { getPieChartOption } from "./revenueChartOptions"
import { getBarChartOption } from "./barChartOptions"
import moment from "moment"
import utilsExportFile from "@/utils/exportFile"
import { cloneDeep } from "lodash-es"
import {
  LineChartOutlined,
  PieChartOutlined,
  BarChartOutlined,
  DotChartOutlined,
  AreaChartOutlined,
  StockOutlined,
  FundOutlined,
  AccountBookOutlined,
} from "@ant-design/icons-vue"
const $api = inject("$api")
const activeKey = ref(1)
const filterForm = ref({
  stationId: undefined,
  timeType: 2,
  year: moment().subtract(1, "year").format("YYYY"),
  month: moment().subtract(1, "month").format("YYYY-MM"),
  exportYear: "",
})

const changeTab = (key) => {
  filterForm.value.stationId = null
  if (key === 2) {
    filterForm.value.year = moment().format("YYYY")
  } else {
    filterForm.value.year = moment().subtract(1, "year").format("YYYY")
  }
  getIncomePlate()
}
const companyList = ref([])
const getConfigList = async () => {
  let params = {
    dimensionType: activeKey.value,
    ...filterForm.value,
    month: filterForm.value.month ? filterForm.value.month.split("-")[1] : null,
    stationId: null,
  }
  const res = await $api.incomeStorageCompanyList(params)
  if (res?.code === 0) {
    companyList.value = res.data.map((item) => ({
      haveIncomeResult: item.haveIncomeResult,
      name: item.station.stationName,
      id: item.station.id,
    }))
  }
}
const cardList = ref([
  {
    label: "售储结合后综合收益",
    value: "--",
    colorClass: "cardBlue",
    icon: LineChartOutlined,
  },
  {
    label: "储能收益",
    value: "--",
    colorClass: "cardPurple",
    icon: PieChartOutlined,
  },
  {
    label: "售储模式增加收益",
    value: "--",
    colorClass: "cardOrange",
    icon: BarChartOutlined,
  },
  {
    label: "售储模式增加收益/MWh",
    value: "--",
    colorClass: "cardPink",
    icon: DotChartOutlined,
  },
  {
    label: "零售电费成本",
    value: "--",
    colorClass: "cardIndigo",
    icon: AreaChartOutlined,
  },
  {
    label: "现货批发侧降本收益",
    value: "--",
    colorClass: "cardCoral",
    icon: StockOutlined,
  },
  {
    label: "储售损耗成本",
    value: "--",
    colorClass: "cardTeal",
    icon: FundOutlined,
    tips: "包含中长期盈亏、需求申报考核、中长期考核、年月错配考核、分摊、现货套利相关指标",
  },
  {
    label: "峰谷平衡电费收益",
    value: "--",
    colorClass: "cardSky",
    icon: AccountBookOutlined,
  },
])
//获取数据详情
let revenueProportion = ref({
  saleIncomeRate: null,
  storageIncomeRate: null,
})
const getIncomePlate = async () => {
  let params = {
    dimensionType: activeKey.value,
    stationId: filterForm.value.stationId,
    timeType: filterForm.value.timeType,
    year:
      filterForm.value.timeType === 1
        ? filterForm.value.month.split("-")[0]
        : filterForm.value.year,

    month:
      filterForm.value.timeType === 1
        ? filterForm.value.month.split("-")[1]
        : null,
  }
  const res = await $api.incomePlate(params)

  if (res?.code === 0) {
    cardList.value = [
      {
        label: "售储结合后综合收益",
        value:
          res.data?.combinedIncome !== undefined &&
          res.data?.combinedIncome !== null
            ? res.data.combinedIncome.toLocaleString()
            : "--",
        colorClass: "cardBlue",
        icon: LineChartOutlined,
      },
      {
        label: "储能收益",
        value:
          res.data?.storageIncome !== undefined &&
          res.data?.storageIncome !== null
            ? res.data.storageIncome.toLocaleString()
            : "--",
        colorClass: "cardPurple",
        icon: PieChartOutlined,
      },
      {
        label: "售储模式增加收益",
        value:
          res.data?.saleIncome !== undefined && res.data?.saleIncome !== null
            ? res.data.saleIncome.toLocaleString()
            : "--",
        colorClass: "cardOrange",
        icon: BarChartOutlined,
      },
      {
        label: "售储模式增加收益/MWh",
        value:
          res.data?.mwSaleIncome !== undefined &&
          res.data?.mwSaleIncome !== null
            ? res.data.mwSaleIncome.toLocaleString()
            : "--",
        colorClass: "cardPink",
        icon: DotChartOutlined,
      },
      {
        label: "零售电费成本",
        value:
          res.data?.retailIncome !== undefined &&
          res.data?.retailIncome !== null
            ? (0 - res.data.retailIncome).toLocaleString()
            : "--",
        colorClass: "cardIndigo",
        icon: AreaChartOutlined,
      },
      {
        label: "现货批发侧降本收益",
        value:
          res.data?.spotWholesaleSaving !== undefined &&
          res.data?.spotWholesaleSaving !== null
            ? res.data.spotWholesaleSaving.toLocaleString()
            : "--",
        colorClass: "cardCoral",
        icon: StockOutlined,
      },
      {
        label: "储售损耗成本",
        value:
          res.data?.lossCost !== undefined && res.data?.lossCost !== null
            ? (0 - res.data.lossCost).toLocaleString()
            : "--",
        colorClass: "cardTeal",
        icon: FundOutlined,
        tips: "包含中长期盈亏、需求申报考核、中长期考核、年月错配考核、分摊、现货套利相关指标",
      },
      {
        label: "峰谷平衡电费收益",
        value:
          res.data?.peakValleyBalanceIncome !== undefined &&
          res.data?.peakValleyBalanceIncome !== null
            ? (0 - res.data.peakValleyBalanceIncome).toLocaleString()
            : "--",
        colorClass: "cardSky",
        icon: AccountBookOutlined,
      },
    ]
    revenueProportion.value.saleIncomeRate = Math.round(
      (res.data?.saleIncome / res.data?.combinedIncome) * 100
    )
    revenueProportion.value.storageIncomeRate = Math.round(
      (res.data?.storageIncome / res.data?.combinedIncome) * 100
    )
    initChart()
    initBarChart(res.data?.chart || [])
  }
}
const changeOption = async () => {
  await getConfigList()
  getIncomePlate()
}

const handleChangeTimeType = async (value) => {
  await getConfigList()
  if (value === 2) {
    filterForm.value.month = null
    filterForm.value.year = moment().subtract(1, "year").format("YYYY")
  } else {
    filterForm.value.month = moment().subtract(1, "month").format("YYYY-MM")
  }
  getIncomePlate()
}
const chartRef = ref(null)
let chart = null
const barChartRef = ref(null)
let barChart = null

const initChart = () => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    const option = getPieChartOption()
    option.series[0].data[0].value = revenueProportion.value.saleIncomeRate
    option.series[0].data[1].value = revenueProportion.value.storageIncomeRate
    chart.setOption(option)
  }
}
const initBarChart = (data) => {
  if (barChartRef.value) {
    barChart = echarts.init(barChartRef.value)
    const option = getBarChartOption()

    option.xAxis.data = data.map((item) => item.shaftName)
    option.series[2].data = data.map((item) => 0 - item.peakValleyBalanceIncome)
    option.series[0].data = data.map((item) => item.saleIncome)
    option.series[1].data = data.map((item) => item.spotWholesaleSaving)
    option.series[3].data = data.map((item) => item.lossCost)
    option.series[4].data = data.map((item) => item.retailIncome)
    //console.log(222, option)
    barChart.setOption(option)
  }
}

const handleResize = () => {
  chart && chart.resize()
  barChart && barChart.resize()
}
const exportIncomePlate = async () => {
  const res = await $api.incomeExportData({ year: filterForm.value.exportYear })
  utilsExportFile.exportFile(res, `收益看板.xlsx`)
}
onMounted(async () => {
  getConfigList()
  getIncomePlate()
  window.addEventListener("resize", () => {
    handleResize()
  })
})
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize)
  chart && chart.dispose()
  barChart && barChart.dispose()
})
</script>
<style lang="less" scoped>
.filterContainer {
  padding: 0px;
  border-radius: 8px;
  width: 350px;
  display: inline-block;
  margin-right: 15px;
  .filterItem {
    width: 350px;
    border: 1px solid #696969;
    padding: 15px 10px;
    margin-bottom: 15px;
    border-radius: 4px;
    background: #141414;
    .filterLabel {
      width: 70px;
      color: rgba(255, 255, 255, 0.85);
      font-size: 14px;
      display: inline-block;
    }
    .filterSelect {
      width: 250px;
      border-radius: 4px;
    }
    .yearSelect {
      width: 210px;
    }
    .exportGroup {
      display: inline-block;
      width: 250px;
    }
    .exportBtn {
      display: inline-block;
      padding: 0;
      margin-left: 5px;
    }
    .filterInput {
      width: 300px;
      background: #1f1f1f;
      border: 1px solid #696969;
      border-radius: 4px;
      color: rgba(255, 255, 255, 0.85);

      &:disabled {
        background: #1f1f1f;
        color: rgba(255, 255, 255, 0.45);
        cursor: not-allowed;
      }
    }
    &:last-child {
      margin-bottom: 0;
    }
  }
}
.pageContainer {
  display: grid;
  grid-template-columns: 300px 1fr;
  min-height: 100vh;
  background: #141414;
  padding: 20px;
}
.nav {
  width: calc(100% - 365px);
  display: inline-block;
  vertical-align: top;
  overflow-x: hidden;
}
.navContent {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 15px;
  border: 1px solid #696969;
  border-radius: 4px;
  height: 270px;
  background: #141414;
  .card {
    border-radius: 8px;
    padding: 10px;
    color: #fff;
    display: flex;
    align-items: center;
    min-height: 100px;
    transition: all 0.3s ease;

    .cardIcon {
      margin-right: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
    }

    .cardContent {
      flex: 1;

      .cardValue {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 4px;
      }

      .cardLabel {
        font-size: 14px;
        opacity: 0.9;
      }
    }

    &.cardBlue {
      background: linear-gradient(135deg, #1890ff, #096dd9);
    }

    &.cardPurple {
      background: linear-gradient(135deg, #722ed1, #531dab);
    }

    &.cardOrange {
      background: linear-gradient(135deg, #fa8c16, #d46b08);
    }

    &.cardPink {
      background: linear-gradient(135deg, #eb2f96, #c41d7f);
    }

    &.cardCoral {
      background: linear-gradient(135deg, #ff6b6b, #ff5252);
    }

    &.cardIndigo {
      background: linear-gradient(135deg, #4c51bf, #3730a3);
    }

    &.cardTeal {
      background: linear-gradient(135deg, #0d9488, #0f766e);
    }

    &.cardSky {
      background: linear-gradient(135deg, #0ea5e9, #0284c7);
    }
  }
}
.revenueChart {
  background: #141414;
  border-radius: 8px;
  padding: 20px;
  width: 250px;
  display: inline-block;
  margin-left: 15px;
  vertical-align: top;
  border: 1px solid #696969;
  border-radius: 4px;
  height: 270px;
  .chartTitle {
    color: #ffffff;
    font-size: 16px;
    margin-bottom: 20px;
  }

  .pieChart {
    height: 130px;
    width: 100%;
  }

  .legendList {
    margin-top: 10px;

    .legendItem {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      background-color: rgba(255, 255, 255, 0.2);
      padding: 0 10px;
      border-radius: 12px;
      height: 24px;
      .legendDot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 8px;

        &.electricity {
          background: #4b9eff;
        }

        &.storage {
          background: #64e8de;
        }
      }

      .legendLabel {
        color: rgba(255, 255, 255, 1);
        margin-right: auto;
      }

      .legendValue {
        color: rgba(255, 255, 255, 1);
      }
    }
  }
}
.barChartContainer {
  margin-top: 20px;
  padding: 20px;
  background: #141414;
  border: 1px solid #696969;
  border-radius: 4px;

  .barChart {
    width: 100%;
    height: 400px;
  }
}
</style>
